package net.tv90.appserveradmin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.tv90.appserveradmin.dao.UserMapper;
import net.tv90.appserveradmin.exception.ServerException;
import net.tv90.appserveradmin.model.Users;
import net.tv90.appserveradmin.service.UserService;
import net.tv90.appserveradmin.util.Assert;
import net.tv90.appserveradmin.util.MD5Utils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Users> implements UserService {

    Map<String, Users> loginUser = new ConcurrentHashMap<>();

    @Override
    public void login(String userId, String password) {
        Assert.assertNotNull("用户名不能为空", HttpStatus.BAD_REQUEST, userId);
        Assert.assertNotNull("密码不能为空", HttpStatus.BAD_REQUEST, password);
        Users one = getById(userId);
        Assert.assertNotNull("该用户不存在", HttpStatus.UNAUTHORIZED, one);
        if (one.getPassword().equals(MD5Utils.md5(MD5Utils.inputPassToNewPass(password)))) {
            StpUtil.login(userId);
            loginUser.put(userId, one);
        } else {
            throw new ServerException("用户名或密码错误", HttpStatus.BAD_REQUEST);
        }
    }

    @Override
    public void logout() {
        String id = StpUtil.getLoginIdAsString();
        if (id == null) {
            throw new ServerException("该用户不存在", HttpStatus.BAD_REQUEST);
        }
        Users user = getById(id);
        if (user == null) {
            throw new ServerException("该用户不存在", HttpStatus.BAD_REQUEST);
        }
        loginUser.remove(id);
        StpUtil.kickout(id);
    }

    @Override
    public Users getCurrentUser() {
        if (!StpUtil.isLogin()) {
            return null;
        }
        String id = StpUtil.getLoginIdAsString();
        if (!loginUser.containsKey(id)) {
            return null;
        }
        return loginUser.get(id);
    }

}
